<?php
/**
 * Created by PhpStorm.
 * User: 轶杰
 * Date: 2016/5/18
 * Time: 20:35
 */
class MyDataBase
{
    var $link;
    function MyDataBase()
    {
        $l=mysqli_connect(DB_HOST,DB_USER,DB_PWD);
        if(!$l) {
            $l = die("数据库炸了" . ":" . mysqli_error($l));
        }
        mysqli_set_charset($l,DB_CHARSET);//字符格式
        mysqli_select_db($l,DB_NAME)//打开表
        or die("数据库炸了");
        $this->link=$l;
    }
    /**
     * @param $table
     * @param $array
     * @return int|string
     */
    function insert($table,$array)
    {
        $keys=join(",",array_keys($array));
        $values="'".join("','",array_values($array))."'";
        $sql="insert into {$table}($keys) values({$values})";
        mysqli_query($this->link,$sql);
        return mysqli_insert_id($this->link);
    }
    /**
     * 更新
     * @param $table
     * @param $array
     * @param null $where
     * @return int
     */
    function update($table,$array,$where=null)
    {
        $str="";
        foreach($array as $key=>$val)
        {
            if($str==null)
            {
                $sep="";
            }
            else{
                $sep=",";
            }
            $str.=$sep.$key."='".$val."'";
        }
        $sql="update {$table} set {$str} ".($where==null?null:"where ".$where);
        mysqli_query($this->link,$sql);
        return mysqli_affected_rows($this->link);
    }
    /**
     * 删除
     * @param $table
     * @param null $where
     * @return int
     */
    function delete($table,$where=null)
    {
        $where=$where==null?null:"where ".$where;
        $sql="delete from {$table} {$where}";
        mysqli_query($this->link,$sql);
        return mysqli_affected_rows($this->link);
    }
    /**
     * 查询一条记录
     * @param $sql
     * @param int $result_type
     * @return array|null
     */
    function fetchOne($sql,$result_type=MYSQLI_ASSOC)
    {
        $result=mysqli_query($this->link,$sql);
        $row=mysqli_fetch_array($result,$result_type);
        return $row;
    }

    /**
     * 查询多条
     * @param $sql
     * @param $result_type
     * @return array
     */
    function fetchAll($sql,$result_type=MYSQLI_ASSOC)
    {
        $result=mysqli_query($this->link,$sql);
        while(@$row=mysqli_fetch_array($result,$result_type))
        {
            $rows[]=$row;
        }
        return $rows;
    }

    /**
     * 查询结果数
     * @param $sql
     * @return int
     */
    function getResultNum($sql)
    {
        $result=mysqli_query($this->link,$sql);
        return mysqli_num_rows($result);
    }

    /**
     * 过滤注入，转义危险字符
     * @param $str
     * @return string
     */
    function checkInjection($str)
    {
        return mysqli_real_escape_string($this->link,$str);
    }
}